
from amplitude.dict import Dict
import os, shutil
from amplitude.lib import id

class Text(Dict):

    def __init__(self, fn="", encoding='UTF-8', **args):
        self.fn = fn
        self.encoding = encoding
        Dict.__init__(self, **args)
        if os.path.exists(self.fn):
            f = open(self.fn, 'rb')
            self.text = f.read().decode(encoding)
            f.close()
        else:
            self.text = u""
            
    def write(self, text=None, fn=None, encoding=None, **args):
        encoding = encoding or self.encoding 
        fn = fn or self.fn 
        text = text or self.text
        if not os.path.exists(os.path.dirname(fn)):
            os.makedirs(os.path.dirname(fn))
        try:
            if os.path.isfile(fn): os.remove(fn)
            f = open(fn, 'wb')
            f.write(text.encode(self.encoding))
            f.close()
        except:
            # maybe there was a low-level disk error; trying writing to a temporary file and copying over instead.
            # (this happens on my SSD when it's being asked to do a LOT of read + write-back operations on a set of files)
#            tempfn = fn+".%s.TEMP" % id.random_id(8, id.hex_chars)   # make sure it's unique
            try:
                f=open(fn, 'wb')
                f.write(text.encode(self.encoding))
                f.close()
            except: # sometimes there's a disk error on SSD
                import time
                time.sleep(.2)
                try:
                    f=open(fn, 'wb')
                    f.write(text.encode(self.encoding))
                    f.close()
                except: # one more try
                    time.sleep(.4)
                    f=open(fn, 'wb')
                    f.write(text.encode(self.encoding))
                    f.close()                    
#            shutil.copy(tempfn, fn)
#           if os.path.isfile(tempfn): os.remove(tempfn)
        
    def write_html(self, fn=None):
        fn = fn or os.path.splitext(self.fn)[0]+'.html'
        t = """<?xml version='1.0' encoding='UTF-8'?>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
    </head>
    <body>
""" + self.markdown() + "\n</body>\n</html>"
        self.write(t, fn=fn)

    def markdown(self, extensions=[]):
        """depends on the markdown module"""
        from markdown import markdown as the_markdown
        return the_markdown(self.text, extensions=extensions)

TextFile = Text
